﻿using Autodesk.Revit.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProjectTest
{
    /// <summary>
    /// 常用外部事件综合 使之能够将事件创建以及具体实现分离
    /// </summary>
    public class CommonExternalEventHandler : IExternalEventHandler
    {
        private static CommonExternalEventHandler mobjHandler;
        public static CommonExternalEventHandler Handler
        {
            get
            {
                if (mobjHandler == null)
                {
                    mobjHandler = new CommonExternalEventHandler();
                }
                return mobjHandler;
            }
        }
        protected ExternalEvent _event;
        protected IList<Action<UIApplication>> _actions = null;
        protected bool _isExecuted = true;

        /// <summary>
        /// 此处直接建立一个事件_event   并建立了事件里一些列动作的容器_actions
        /// </summary>
        public CommonExternalEventHandler()
        {
            _event = ExternalEvent.Create(this);
            _actions = new List<Action<UIApplication>>();
        }

        /// <summary>
        /// 延迟发生动作  此处传入一些动作 付给事件的动作容器  并执行 
        /// </summary>
        /// <param name="act"></param>
        /// <returns></returns>
        public bool DelayRunAction(Action<UIApplication> act)
        {
            if (act == null)
            {
                return false;
            }

            _actions.Add(act);
            _isExecuted = false;
            _event.Raise();

            return true;
        }

        public void Execute(Autodesk.Revit.UI.UIApplication app)
        {
            if (_actions.Any())
            {
                _isExecuted = true;

                _actions.ToList().ForEach(action =>
                    action(app)
                );

                _actions.Clear();
            }
        }

        public string GetName()
        {
            //return nameof(ExternalEventHandler);
            return "ExternalEventHandler";
        }
    }
}
